package com.kqzz.common.exception;

import java.io.IOException;
import java.util.Arrays;
import java.util.Optional;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.google.gson.Gson;
import com.kqzz.common.api.response.Response;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;

@Component("customLoginSuccessHandler")
public class CustomLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
	
	private RequestCache requestCache = new HttpSessionRequestCache();

	@Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws ServletException, IOException {

        // 判断是不是ajax请求
        String ajax = Optional.ofNullable(request
                .getParameterMap().get("_ajax")).flatMap(t -> Arrays.stream(t).findFirst()
        ).orElse(StrUtil.EMPTY);

        /**
         * {@link CustomLoginUrlAuthenticationEntryPoint}获取认证时的url，模仿 {@link DefaultSavedRequest}行为
         */
        System.out.println(request.getParameter("callbackurl"));
        String base64EncodeSavedRequestUrl = Optional.ofNullable(request
                .getParameterMap().get("callbackurl")).flatMap(t -> Arrays.stream(t).findFirst()
        ).orElse(StrUtil.EMPTY);

        String savedRequestUrl = Base64.decodeStr(base64EncodeSavedRequestUrl);
		SavedRequest savedRequest = requestCache.getRequest(request, response);

        String targetUrlParameter = getTargetUrlParameter();
		if (isAlwaysUseDefaultTargetUrl()
                || (targetUrlParameter != null && StringUtils.hasText(request
                .getParameter(targetUrlParameter)))) {
            requestCache.removeRequest(request, response);
            super.onAuthenticationSuccess(request, response, authentication);

            return;
        }
		
        clearAuthenticationAttributes(request);

		
        if (Boolean.parseBoolean(ajax)) {
        	Gson gson = new Gson();
//            HashMap<Object, Object> returnData = new HashMap<>();
//            returnData.put("url", savedRequestUrl);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(gson.toJson(new Response().success(savedRequestUrl)));
        } else {
            getRedirectStrategy().sendRedirect(request, response, savedRequestUrl);
        }
  }
}
